package cn.lopr.im.android.mvp.model;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

import cn.lopr.im.android.bean.CallbackResult;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.Constant;
import cn.lopr.im.android.common.OnCallBackListener;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.mvp.contact.IHomeContact;
import cn.lopr.im.android.utils.Apis;
import cn.lopr.im.android.utils.HttpUtils;

/**
 * @author shuangyang7
 * @date 2021/1/3 15:48
 */
public class HomeModel implements IHomeContact.IHomeModel {

    @Override
    public void getFriend(final OnCallBackListener<CallbackResult<List<User>>, String> onCallBackListener) {

        Type userType = new TypeToken<CallbackResult<List<User>>>() {
        }.getType();

        HttpUtils.doGetForResult(Apis.WebApis.GET_FRIEND.getValue(), "", data -> {
            if (TextUtils.isEmpty(data)) {
                onCallBackListener.failure(Constant.CALLBACK_ERROR_MESSAGE);
                return;
            }

            CallbackResult<List<User>> userResult = new Gson().fromJson(data, userType);

            if (userResult.getStatus() == Constant.ResponseCode.SUCCESS.getCode()) {
                onCallBackListener.success(userResult);

            } else {
                onCallBackListener.failure(userResult.getMsg());

            }
        });
    }

    @Override
    public void getOffline(String token, OnCallBackListener<CallbackResult<List<Message>>, String> onCallBackListener) {
        Type messageType = new TypeToken<CallbackResult<List<Message>>>() {
        }.getType();

        HttpUtils.doGetForResult(Apis.WebApis.GET_OFFLINE_MESSAGE.getValue(), "", token, data -> {
            if (TextUtils.isEmpty(data)) {
                onCallBackListener.failure(Constant.CALLBACK_ERROR_MESSAGE);
                return;
            }
            CallbackResult<List<Message>> messageResult = new Gson().fromJson(data, messageType);
            if (messageResult.getStatus() == Constant.ResponseCode.SUCCESS.getCode()) {
                onCallBackListener.success(messageResult);

            } else {
                onCallBackListener.failure(messageResult.getMsg());
            }
        });
    }
}
